# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import execjs

requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


"""
毒app
参考https://github.com/luo1994/du-app-sign
"""


class Du_App():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            'Host': "app.poizon.com",
            # 'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)"
            #               " Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.4.501 NetType/WIFI "
            #               "MiniProgramEnv/Windows WindowsWechat",
            "User-Agent": "Mozilla/5.0 (Linux; Android 5.0.2; CHE-TL00H Build/HonorCHE-TL00H; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/045114 Mobile Safari/537.36/duapp/4.30.6(android;5.0.2)",
            'appid': "wxapp",
            'appversion': "4.4.0",
            'content-type': "application/x-www-form-urlencoded",
            'Accept-Encoding': "gzip, deflate",
            'Accept': "*/*",
        }

    # 获取列表信息
    def get_contents(self):
        # 列表
        brand_list_url = self.get_brand_list_url(1, 4)
        html = HttpUtils.do_request("GET", brand_list_url, self.headers, "")
        data_json = json.loads(html.text)
        lastId = data_json['data']['lastId']
        for d in data_json['data']['list']:
            dict_data = dict()
            dict_data['logoUrl'] = d['logoUrl'] # logUrl
            dict_data['productId'] = d['productId']  # id
            dict_data['title'] = d['title']  # 标题
            dict_data['price'] = d['price']  # 价格
            dict_data['soldNum'] = d['soldNum']  # 付款数量
            # 商品详情
            product_detail_url = self.get_product_detail_url(d['productId'])
            html1 = HttpUtils.do_request("GET", product_detail_url, self.headers, "")
            data_json_detail = json.loads(html1.text)
            dict_data['color'] = data_json_detail['data']['detail']['color']  # 配色
            dict_data['articleNumber'] = data_json_detail['data']['detail']['articleNumber']  # 货号
            dict_data['authPrice'] = data_json_detail['data']['detail']['authPrice']  # 发售价格
            dict_data['sellDate'] = data_json_detail['data']['detail']['sellDate']  # 发售日期
            dict_data['size'] = "|".join(data_json_detail['data']['detail']['sizeList']) # 尺码
            print(str(dict_data))

    # 商品品类列表接口 lastId=1页号  tabId=4 球鞋
    def get_brand_list_url(self, lastId, tabId):
        with open('sign.js', 'r', encoding='utf-8') as f:
            all_ = f.read()
            ctx = execjs.compile(all_)
            sign = ctx.call('getSign',
                            'lastId{}limit20tabId{}19bc545a393a25177083d4a748807cc0'.format(lastId, tabId))
            brand_list_url = 'https://app.poizon.com/api/v1/h5/index/fire/shoppingTab?' \
                             'tabId={}&limit=20&lastId={}&sign={}'.format(tabId, lastId, sign)
            return brand_list_url


    # 商品详情接口 productId商品ID
    def get_product_detail_url(self, productId):
        with open('sign.js', 'r', encoding='utf-8') as f:
            all_ = f.read()
            ctx = execjs.compile(all_)
            sign = ctx.call('getSign',
                            'productId{}productSourceNamewx19bc545a393a25177083d4a748807cc0'.format(productId))
            product_detail_url = 'https://app.poizon.com/api/v1/h5/index/fire/flow/product/detail?' \
                                 'productId={}&productSourceName=wx&sign={}'.format(productId, sign)
            return product_detail_url


    # 关键词搜索商品接口
    def get_search_by_keywords_url(self, page, sortMode, sortType):
        with open('sign.js', 'r', encoding='utf-8') as f:
            all_ = f.read()
            ctx = execjs.compile(all_)
            # 53489
            sign = ctx.call('getSign',
                            'limit20page{}sortMode{}sortType{}titleajunionId19bc545a393a25177083d4a748807cc0'
                            .format(page, sortMode, sortType))
            search_by_keywords_url = 'https://app.poizon.com/api/v1/h5/product/fire/search/list?' \
                                     'title=aj&page={}&sortType={}&sortMode={}&limit=20&unionId=&sign={}'\
                .format(page, sortType, sortMode, sign)

            return search_by_keywords_url


    # 最近购买接口 第一次lastId为0.第二次取返回lastId值
    def get_recensales_list_url(lastId, productId):
        with open('sign.js', 'r', encoding='utf-8') as f:
            all_ = f.read()
            ctx = execjs.compile(all_)
            sign = ctx.call('getSign',
                            'lastId{}limit20productId{}sourceAppapp19bc545a393a25177083d4a748807cc0'
                            .format(lastId, productId))
            recensales_list_url = 'https://app.poizon.com/api/v1/h5/product/fire/recentSoldList?' \
                                  'productId={}&lastId={}&limit=20&sourceApp=app&sign={}'.\
                format(productId, lastId, sign)
            return recensales_list_url


if __name__ == '__main__':
    du_app = Du_App()
    du_app.get_contents()